package org.osomit.sacct.security.utils;

/**
 * Shuffle the character set and re-map the String to another String for security protection.
 *
 * @author Jian Fang (John.Jian.Fang@gmail.com)
 *
 * Date: Jun 26, 2009
 */
public class Shuffler {

    private static final char[] PRINTABLE_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

    private static char[] createShuffledCharacterSet(int leftShiftLength){
    	int actualLeftShiftLength = 0;

    	if(leftShiftLength <= 0){
    		//invalid left shift value
    		actualLeftShiftLength = 0;
    	}

    	actualLeftShiftLength = leftShiftLength;
    	if(leftShiftLength >= PRINTABLE_CHARACTERS.length){
    		//wrap around the Character set size
    		actualLeftShiftLength = leftShiftLength%PRINTABLE_CHARACTERS.length;
    	}

    	if(actualLeftShiftLength == 0){

    		return PRINTABLE_CHARACTERS;
    	}else{
    		StringBuffer sb = new StringBuffer(PRINTABLE_CHARACTERS.length);
    		String original = new String(PRINTABLE_CHARACTERS);
    		sb.append(original.substring(actualLeftShiftLength)).append(original.substring(0,actualLeftShiftLength));

    		return sb.toString().toCharArray();
    	}
    }

    public static String shuffle(String message, int leftShiftLength){
    	if(message == null )
    		return null;

    	if(message.length() <=0)
    		return message;

    	char[] newCharSet = createShuffledCharacterSet(leftShiftLength);
   		String original = new String(PRINTABLE_CHARACTERS);
   		StringBuffer sb = new StringBuffer(message.length());
   		for(char ch : message.toCharArray()){
   			int index = original.indexOf(ch);
   			sb.append(newCharSet[index]);
   		}

    	return sb.toString();
    }

    public static String unshuffle(String message, int leftShiftLength){
    	if(message == null)
    		return null;

    	if(message.length() <= 0)
    		return message;

    	char[] newCharSet = createShuffledCharacterSet(leftShiftLength);
   		String newone = new String(newCharSet);
   		StringBuffer sb = new StringBuffer(message.length());
   		for(char ch : message.toCharArray()){
   			int index = newone.indexOf(ch);
   			sb.append(PRINTABLE_CHARACTERS[index]);
   		}

    	return sb.toString();
    }
}
